package com.bloveoacom.weichi.activity;

import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bloveoacom.base.BaseActivity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.http.MessageModel;
import com.bloveoacom.http.RxBus;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.ActivityUtil;
import com.bloveoacom.util.DataUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.bean.CreateEosWalletBean;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weichi.bean.UserBean;
import com.bloveoacom.weight.DelEditText;
import com.bloveoacom.weight.LlkjToolBar;

import org.reactivestreams.Publisher;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bloveoacom.http.MessageModel.TU_TYPE_UPDATEUSERINFO;
import static com.bloveoacom.util.AESCipher.KEY;


public class CreateWalletActivity extends BaseActivity {
    @BindView(R.id.etpaypwd)
    DelEditText etpaypwd;
    @BindView(R.id.etpaypwd2)
    DelEditText etpaypwd2;
    @BindView(R.id.et_wallet_name)
    DelEditText etWalletName;
    @BindView(R.id.title_bar)
    LlkjToolBar mToolbar;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_createwallet;
    }

    @Override
    public void initView() {
        mToolbar.setToolBar("创建",
                true, "", R.drawable.ic_back, true, "", R.drawable.ic_search);
    }


    @Override
    protected View getViewSetTB() {
        return mToolbar;
    }

    @Override
    public void initData() {

    }

    @Override
    public void getBundleExtras(Bundle extras) {

    }

    @Override
    public void initListener() {

    }


    @OnClick({R.id.btn_register})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                loginOrRegister();
                break;
            default:
                break;
        }
    }

    private String paypwd, walletname,paypwd2;

    private void loginOrRegister() {
        paypwd = etpaypwd.getText().toString().trim();
        paypwd2 = etpaypwd2.getText().toString().trim();
        walletname = etWalletName.getText().toString().trim();
        if (StringUtils.isEmpty(paypwd)) {
            ToastUtil.makeShortText(mContext, "请输入支付密码");
            return;
        }
        if(!paypwd.equals(paypwd2)){
            ToastUtil.makeShortText(mContext, "两次密码不一致");
            return;
        }
        if (!DataUtil.isValidEOSAccount(walletname)) {
            ToastUtils.showLong("钱包格式不对,必须是12位，\n数字1-5，字母a-z不能大写");
            return;
        }

        BaseSubscriber2<HttpResult<Object>> baseSubscriber2 = HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance().getToken()).subscribeOn(Schedulers.io()).flatMap(new Function<HttpResult<Object>, Publisher<HttpResult<Object>>>() {
            @Override
            public Publisher<HttpResult<Object>> apply(HttpResult<Object> objectHttpResult) throws Exception {
                if (objectHttpResult.isOk()) {
                    Object o = objectHttpResult.data;
                    SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                    String s = AESCipher.decryptAES(simpleBean.timeStamp);
                    CreateEosWalletBean transInfoBean = new CreateEosWalletBean(paypwd, s);
                    String s1 = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean), KEY);
                    return HttpMethods.getInstance().getHttpService().registerWallet(UserInfoBean.getInstance().getToken(), walletname, s1);
                } else {
                    return Flowable.error(new ApiException(objectHttpResult.code, objectHttpResult.msg));
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new BaseSubscriber2<HttpResult<Object>>(this) {
            @Override
            public void onNext(HttpResult<Object> o) {
                if (o.isOk()) {
                    String json = GsonUtil.GsonString(o.data);
                    String publicKey="",privateKey="";
                    UserBean userRegisterBean = GsonUtil.GsonToBean(json, UserBean.class);
                    UserInfoBean.getInstance().setWalletAccount(userRegisterBean.walletAccount);
                    try {
                         publicKey = AESCipher.decryptAES(userRegisterBean.publicKey);
                         privateKey = AESCipher.decryptAES(userRegisterBean.privateKey);
                    } catch (InvalidKeyException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                        e.printStackTrace();
                    } catch (InvalidAlgorithmParameterException e) {
                        e.printStackTrace();
                    } catch (IllegalBlockSizeException e) {
                        e.printStackTrace();
                    } catch (BadPaddingException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    UserInfoBean.getInstance().setPubilcKey(publicKey);
                    UserInfoBean.getInstance().setPrivateKey(privateKey);
                    ActivityUtil.startActivity(mContext, WalletInfoActivity.class);
                    RxBus.getInstance().send(new MessageModel(TU_TYPE_UPDATEUSERINFO));
                    finish();
                } else {
                    ToastUtil.makeShortText(mContext, o.msg);
                }
            }
        });
        addDispose(baseSubscriber2);
    }

}
